package com.sardine.base.esm.binding;

import com.sardine.base.esm.session.EsmSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 上海京东到家元信信息技术有限公司<br>
 * Created with IntelliJ IDEA.
 * Date:2017/5/23
 * Time:16:30
 * esm 映射代理工厂
 * @author daifeng<br>
 *         daifeng@imdada.cn
 * @since JDK 1.7 <br>
 * Copyright (c) 2017 imdada System Incorporated All Rights Reserved.
 */
public class EsmMapperProxyFactory<T> {
    private static final Logger logger = LoggerFactory.getLogger(EsmMapperProxyFactory.class);
    private final Class<T> mapperInterface;
    private Map<Method, EsmMapperMethod> methodCache = new ConcurrentHashMap<Method, EsmMapperMethod>();
    public EsmMapperProxyFactory(Class<T> mapperInterface) {
        this.mapperInterface = mapperInterface;
    }

    public Class<T> getMapperInterface() {
        return mapperInterface;
    }
    public Map<Method, EsmMapperMethod> getMethodCache() {
        return methodCache;
    }
    protected T newInstance(EsmAnnotationMapperProxy<T> mapperProxy) {
        logger.info("esm annotation 代理映射...");
        return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface}, mapperProxy);
    }
    public T newInstance(EsmSession sqlSession) {
        //annotation的接口映射对象
        final EsmAnnotationMapperProxy<T> mapperProxy = new EsmAnnotationMapperProxy<T>(sqlSession, mapperInterface, methodCache);
        return newInstance(mapperProxy);
    }
}
